<?php

/**
 * This is the model class for table "{{booking}}".
 *
 * The followings are the available columns in table '{{booking}}':
 * @property integer $id
 * @property integer $order_id
 * @property integer $bookable_resource_id
 * @property integer $booking_status_id
 * @property integer $booking_amount
 * @property string $start_time
 * @property string $end_time
 * @property integer $user_id
 * @property string $create_time
 * @property string $update_time
 * @property integer $update_user_id
 * @property integer $status
 */
class BSMBooking extends CActiveRecord
{
    const STATUS_BOOKED = 1;
    const STATUS_PAYING = 2;
    const STATUS_SAVED = 3;
    const STATUS_CANCEL = 4;
    
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{booking}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('order_id, bookable_resource_id, booking_status_id, start_time, end_time, create_time', 'required'),
			array('order_id, bookable_resource_id, booking_status_id, booking_amount, user_id, update_user_id, status', 'numerical', 'integerOnly'=>true),
			array('update_time', 'safe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, order_id, bookable_resource_id, booking_status_id, booking_amount, start_time, end_time, user_id, create_time, update_time, update_user_id, status', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
            'bookableResource'=>array(self::BELONGS_TO, 'BSMBookableResource', 'bookable_resource_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'order_id' => 'Order',
			'bookable_resource_id' => 'Bookable Resource',
			'booking_status_id' => 'Booking Status',
			'booking_amount' => 'Booking Amount',
			'start_time' => 'Start Time',
			'end_time' => 'End Time',
			'user_id' => 'User',
			'create_time' => 'Create Time',
			'update_time' => 'Update Time',
			'update_user_id' => 'Update User',
			'status' => 'Status',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('order_id',$this->order_id);
		$criteria->compare('bookable_resource_id',$this->bookable_resource_id);
		$criteria->compare('booking_status_id',$this->booking_status_id);
		$criteria->compare('booking_amount',$this->booking_amount);
		$criteria->compare('start_time',$this->start_time,true);
		$criteria->compare('end_time',$this->end_time,true);
		$criteria->compare('user_id',$this->user_id);
		$criteria->compare('create_time',$this->create_time,true);
		$criteria->compare('update_time',$this->update_time,true);
		$criteria->compare('update_user_id',$this->update_user_id);
		$criteria->compare('status',$this->status);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * @return CDbConnection the database connection used for this class
	 */
	public function getDbConnection()
	{
		return Yii::app()->bookingdb;
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return BSMBooking the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

    protected function beforeValidate()
    {
        if ($this->isNewRecord) {
            $this->create_time = date('Y-m-d H:i:s');
            $this->user_id = yii::app()->user->id;
        }

        return parent::beforeValidate();
    }

    protected function beforeSave() {
        if (parent::beforeSave()) {
            if (!$this->isNewRecord) {
                $this->update_time = date('Y-m-d H:i:s');
                $this->update_user_id = yii::app()->user->id;
            }
            
            return true;
        } else {
            return false;
        }
    }
    
    public function getList($resourceId, $date, $startTime = NULL, $endTime = NULL, $userId = NULL)
    {
        $criteria = new CDbCriteria;
        $criteria->with = array(
            'bookableResource',
        );

        $criteria->addCondition("bookableResource.resource_id = :resource_id");
        $criteria->params[':resource_id'] = $resourceId;
        
        $criteria->addCondition("booking_status_id <> :booking_status_id");
        $criteria->params[':booking_status_id'] = self::STATUS_CANCEL;
        
        $startDate = $startTime == NULL ? $date->format("Y-m-d") :
            $date->format("Y-m-d") . ' ' . $startTime;
        $endDate = $endTime == NULL ? $date->format("Y-m-d") . ' 23:59:59' :
            $date->format("Y-m-d") . ' ' . $endTime;

        $criteria->addBetweenCondition('start_time', $startDate, $endDate);

        if ($userId != NULL) {
            $criteria->addCondition("bookableResource.user_id = :user_id");
            $criteria->params[':user_id'] = $userId;
        }
        
        $list = self::model()->findAll($criteria);
        
        return $list;
    }
}
